package top.archiesean.authorize.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClientRepository;
import org.springframework.stereotype.Service;
import top.archiesean.authorize.service.IRegisteredClient;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

/**
 * @author ArchieSean
 * @description 客户端信息
 * @date 2024-02-18 13:10
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class RegisteredClientImpl implements IRegisteredClient {
    private final RegisteredClientRepository jdbcRegisteredClientRepository;

    /**
     * @param clientId 客户端id
     * @param scope    当前申请的scope
     * @return map
     */
    @Override
    public Map<String, Object> findOneByClientId(String clientId, String scope) {
        RegisteredClient client = jdbcRegisteredClientRepository.findByClientId(clientId);
        Set<String> scopes = Optional.of(client)
                .orElseThrow(() -> new OAuth2AuthenticationException("clientId 不合法"))
                .getScopes();
        //遍历封装scope，用户请求的scope和授权时需要传递的scope一致
        HashMap<String, Object> map = new HashMap<>();
        scopes.forEach(item -> {
            if (item.equalsIgnoreCase(scope)) {
                map.put(item, true);
            }
        });
        return map;
    }
}
